# coding:utf8

from appserver import db_store
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func
from models.entity.facility import Facility
from models.entity.device import Device

"""
设备类型
"""


class FacilityWithDevice(db_store.Model):
    __tablename__ = "facility_with_device"
    __main__ = "main"

    # autoincrement=True,
    # id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    facility_id = db_store.Column(db_store.Integer, db_store.ForeignKey('facility.id'), primary_key=True, nullable=False, comment=u"设施id")
    device_id = db_store.Column(db_store.Integer, db_store.ForeignKey('devices.id'), primary_key=True, nullable=False, comment=u"设备id")

    def __repr__(self):
        return "<FacilityWithDevice %s>" % self.id

    def save(self):
        try:
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            db_store.session.rollback()
            print(e)
            return False

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False

    @staticmethod
    def get_facility_by_device(device_id):
        rlist=[]
        connectors=FacilityWithDevice.query.filter_by(device_id=device_id).all()
        for item in connectors:
            rlist.append(Facility.query.fitler_by(id=item.facility_id).all())
        return rlist

    @staticmethod
    def get_device_by_facility(facility_id):
        rlist=[]
        connectors=FacilityWithDevice.query.filter_by(facility_id=facility_id).all()
        # print('connectors-f_d', connectors.facility_id, connectors.device_id)
        for item in connectors:
            # print('item', item.device_id)
            rlist.append(Device.query.filter_by(id=item.device_id).first())
        return rlist

    @staticmethod
    def get_all():
        return FacilityWithDevice.query.all()